﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.Configuration;

public partial class AddNewProducts_Manh : System.Web.UI.Page
{
    private SqlCommand CMD;
    private DataTable TB;
    private DataSet DS;
    private SqlConnection CON;
    private SqlDataAdapter DA;
    protected void Page_Load(object sender, EventArgs e)
    {

            TB = new DataTable();
        string connectString = WebConfigurationManager.ConnectionStrings["connect"].ConnectionString;
        CON = new SqlConnection(connectString);
        if(!IsPostBack)
        {
        if (CON.State == ConnectionState.Open)
                CON.Close();
        else
                CON.Open();
        CMD = new SqlCommand("select * from Category", CON);
        DA = new SqlDataAdapter(CMD);
        DA.Fill(TB);
        DropDownListCategory.DataSource = TB;
        DropDownListCategory.DataTextField = "CategoryName";
        DropDownListCategory.DataValueField = "Id";
        DropDownListCategory.DataBind();
        CON.Close();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            if (CON.State == ConnectionState.Open)
                CON.Close();
            else
                CON.Open();
            CMD = new SqlCommand("addProduct", CON);
            CMD.CommandType = CommandType.StoredProcedure;
            CMD.Parameters.Add("@productid", SqlDbType.Int).Value = Convert.ToInt32(txtID.Text);
            CMD.Parameters.Add("@productname", SqlDbType.NVarChar).Value = txtProductName.Text;
            CMD.Parameters.Add("@productcategory", SqlDbType.NVarChar).Value = DropDownListCategory.SelectedValue.ToString();
            string img = FileUpload1.FileName;
            CMD.Parameters.Add("@productimage", SqlDbType.NVarChar).Value = "~\\ImgProduct\\" + img;
            CMD.Parameters.Add("@productprice", SqlDbType.Int).Value = Convert.ToInt32(txtProductPrice.Text);

            CMD.ExecuteNonQuery();
            //upload image on server
            FileUpload1.SaveAs(Server.MapPath("~\\ImgProduct\\" + img));
            Response.Redirect("Default.aspx");
        }
        catch (SqlException ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            CON.Close();
        }
    }
}